package routers

import (
	"5title_gin/global"
	"5title_gin/internal/api/middleware"
	"5title_gin/internal/api/routers/auth"
	"5title_gin/internal/api/routers/business"
	"5title_gin/internal/api/routers/system"
	"5title_gin/internal/api/routers/user"
	"fmt"
	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	gs "github.com/swaggo/gin-swagger"
	"go.uber.org/zap"
)

// Run 启动HTTP服务器
func Run() {
	// 设置Gin模式（开发/生产）
	gin.SetMode(global.Config.System.Mode)
	r := gin.Default()

	// 注册静态文件路由
	r.Static("/uploads", "uploads")

	// 注册Swagger文档路由
	r.GET("/swagger/*any", gs.WrapHandler(swaggerFiles.Handler))

	// 获取服务器地址
	addr := global.Config.System.Addr()

	// 注册全局中间件
	registerGlobalMiddlewares(r)

	// 注册API路由
	registerAPIRoutes(r)

	// 启动服务器
	zap.S().Infof("服务器正在启动，监听地址: %s", addr)
	if global.Config.System.Mode == "release" {
		fmt.Printf("✨ 服务器启动成功！(≧▽≦) 🎉，访问地址为：%s\n", addr)
	}

	if err := r.Run(addr); err != nil {
		zap.S().Fatalf("服务器启动失败: %v", err)
	}
}

// registerGlobalMiddlewares 注册全局中间件
func registerGlobalMiddlewares(r *gin.Engine) {
	r.Use(middleware.Cors())
	r.Use(middleware.LimitMiddleware(5))
	r.Use(middleware.LoggerMiddleware())
}

// registerAPIRoutes 注册API路由
func registerAPIRoutes(r *gin.Engine) {
	// 公开API路由组
	publicAPI := r.Group("api")

	// 需要认证的API路由组
	privateAPI := r.Group("api")
	privateAPI.Use(middleware.AuthMiddleware)

	// 注册权限相关路由
	auth.AuthRouter(privateAPI, publicAPI)
	// 注册用户相关路由
	user.UserRouter(privateAPI, publicAPI)

	// 注册系统相关路由
	system.RoleRouter(privateAPI, publicAPI)
	system.SysDeptRouter(privateAPI, publicAPI)
	system.SysMenuRouter(privateAPI, publicAPI)
	system.SysOssRouter(privateAPI, publicAPI)

	// 注册业务模块路由
	business.OrdersRouter(privateAPI, publicAPI)
}
